'use strict';
const {
	verifyToken
} = require("login-common")
let db = uniCloud.database({
	throwOnNotFound: false
})
exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('event : ', event)

	const {
		api,
		token,
		content,
		title,
		action
	} = event;
	const payload = verifyToken(token) // token携带的信息解密出来 得到 openid
	console.log(payload, '55');
	if (api === 'addMdApid') { // 发布留言
		return await db.collection("memorandum").add({
			openid: payload.openid,
			content,
			createTime: Date.now(),
			title,
		})
	}
	if (api === 'updateMdApid') { // 更新留言
		return await db.collection("memorandum").doc(
			event._id
		).update({
			content,
			createTime: Date.now(),
			title,
		})
	}
	if (api === 'searchMd') { // 模糊查询
		// 查询一个字段 db.collection.where({name:new RegExp(x)}).get()
		const dbCmd = db.command // 取指令
		return await db.collection("memorandum").where(dbCmd.or({ // 查询两个字段
			title: new RegExp(event.keyword, 'i')
		}, {
			content: new RegExp(event.keyword, 'i')
		})).get()
	}
	if (api === 'getMemorandumApi') { // 获取备忘录
		return await db.collection("memorandum").where({
			openid: payload.openid
		}).orderBy('createTime', 'desc').get()
	}
	if (api === 'MdById') {
		if (action == 'get') return await db.collection("memorandum").doc(
			event._id
		).get()
		if (action == 'delete') return await db.collection("memorandum").doc(
			event._id
		).remove()
	}
	//返回数据给客户端
	return event
};
